﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExcelGenerator.SpreadSheet
{
    public class Worksheet
    {
        private StringBuilder sb;
        private string _title;

        public List<Column> Columns;
        public List<Row> Rows;

        public Worksheet(String title)
        {
            Columns = new List<Column>();
            Rows = new List<Row>();
            sb = new StringBuilder();

            _title = title;
        }

        public string title
        {
            get
            {
                return _title;
            }
            set
            {
                _title = value;
            }
        }

        public StringBuilder encodeCells()
        {
            foreach (Column column in Columns)
            {
                if (column.Width > 0)
                {
                    sb.Append("<Column ss:Width=\"" + column.Width + "\" ss:AutoFitWidth=\"" + ((column.AutoFitWidth) ? 1 : 0) + "\" />");
                }
                else
                {
                    sb.Append("<Column ss:AutoFitWidth=\"" + ((column.AutoFitWidth) ? 1 : 0) + "\" />");
                }
            }

            foreach (Row row in Rows)
            {
                //inicia nova linha
                sb.Append("<Row>");
                //checa se a linha possui span maior que 1
                if (row.span > 1)
                {
                    Cell cell = row.Cells[0];
                    sb.Append("<Cell ss:MergeAcross=\"" + (row.span - 1) + "\" ss:StyleID=\"" + cell.style + "\"><Data ss:Type=\"" + cell.type + "\">" + cell.Value + "</Data></Cell>");
                }
                else
                {
                    //Insere as celulas
                    foreach (Cell cell in row.Cells)
                    {
                        sb.Append("<Cell ss:MergeAcross=\"" + (cell.span - 1) + "\" ss:StyleID=\"" + cell.style + "\"><Data ss:Type=\"" + cell.type + "\">" + cell.Value + "</Data></Cell>");
                    }
                }
                //Fecha a linha
                sb.Append("</Row>");
            }
            
            return sb;
        }
    }
}
